package com.zretc.emptraining.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class MyFilter
 */
@WebFilter("/*")
public class MyFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public MyFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// 设置请求编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");

		// 将父类对象ServletRequest转化为HttpServletRequest对象
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 获取相对路径uri
		String uri = req.getRequestURI();

		// 对请求进行判断是否已经登录了
		if (req.getSession().getAttribute("username") != null) {
			// 不为空，表示已经的登陆过了，直接放行
			chain.doFilter(request, response);
		} else if (uri.endsWith("Login.jsp") || uri.endsWith("LoginServlet") ||  uri.endsWith("MessageLogin.jsp") ||  uri.endsWith("CodeServlet") || uri.endsWith("MessageLoginServlet") || uri.endsWith("FindPwd.jsp") || uri.endsWith(".css") || uri.endsWith(".js")) {
			// 放行
			chain.doFilter(request, response);
		} else {
			// 重定向
			res.sendRedirect("Login.jsp");
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
